import { useDicts } from '@/layout/hooks/useDictOptions';
import dayjs from "dayjs";
import editForm from "./form.vue";
import { handleTree } from "@/utils/tree";
import feedback from "@/utils/feedback";
import { usePublicHooks } from "@/views/hooks";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "./types";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";

//api
import {
    NavDelete,
    NavList,
    NavAdd,
    NavEdit,
    NavDetail
} from "@/api/edu/nav";

export function useHook() {
    //表单查询字段
    const form = reactive({

        navName: null,

        status: null,
    });

    const formRef = ref();
    const dataList = ref([]);
    const loading = ref(true);
    const { tagStyle } = usePublicHooks();

    //查询字典 格式: type1,type2 返回 optionsData.type1 ptionsData.type2
    const { optionsData } = useDicts<any>("sys_normal_disable")


    //表格字段
    const columns: TableColumnList = [

        {
            label: "id",
            prop: "id",
            align: "left"
        },

        {
            label: "导航名称",
            prop: "navName",
            minWidth: 200
        },

        {
            label: "打开方式",
            prop: "target",
            minWidth: 200
        },

        {
            label: "链接地址",
            prop: "targetUrl",
            minWidth: 200
        },

        {
            label: "状态",
            prop: "status",
            minWidth: 100,
            cellRenderer: ({ row, props }) => (
                <el-tag size={props.size} style={tagStyle.value(row.status)}>
                    {row.status === 0 ? "启用" : "停用"}
                </el-tag>
            )
        },

        {
            label: "排序",
            prop: "orderCount",
            minWidth: 200
        },

        {
            label: "创建者",
            prop: "createBy",
            minWidth: 200
        },

        {
            label: "创建时间",
            minWidth: 200,
            prop: "createTime",
            formatter: ({ createTime }) => {
                dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
            }

        },

        {
            label: "更新者",
            prop: "updateBy",
            minWidth: 200
        },


        {
            label: "备注",
            prop: "remark",
            minWidth: 200
        },



        {
            label: "操作",
            fixed: "right",
            width: 210,
            slot: "operation"
        }
    ];


    function handleSelectionChange(val) {
        console.log("handleSelectionChange", val);
    }

    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }

    async function onSearch() {
        loading.value = true;
        NavList(form).then(res => {
            dataList.value = res.data;
            loading.value = false;
        })
    }

    /**
     * 装载转换其他数据
     * @param treeList
     * @returns
     */
    function formatHigherDeptOptions(treeList) {
        // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
        if (!treeList || !treeList.length) return;
        const newTreeList = [];
        for (let i = 0; i < treeList.length; i++) {
            treeList[i].disabled = treeList[i].status === 0 ? true : false;
            formatHigherDeptOptions(treeList[i].children);
            newTreeList.push(treeList[i]);
        }
        return newTreeList;
    }

    function openDialog(title = "新增", row?: FormItemProps) {
        console.log("optionsData->新增", optionsData);

        addDialog({
            title: title,
            props: {
                formInline: {
                    higherOptions: formatHigherDeptOptions(cloneDeep(dataList.value)),//状态其他数据
                    dictOptionData: optionsData,
                    id: row?.id ?? null,

                    navName: row?.navName ?? null,

                    target: row?.target ?? null,

                    targetUrl: row?.targetUrl ?? null,

                    status: row?.status ?? null,

                    orderCount: row?.orderCount ?? null,

                    createBy: row?.createBy ?? null,

                    createTime: row?.createTime ?? null,

                    updateBy: row?.updateBy ?? null,

                    updateTime: row?.updateTime ?? null,

                    remark: row?.remark ?? null,

                    delFlag: row?.delFlag ?? null,

                    revision: row?.revision ?? null,

                    tenantId: row?.tenantId ?? null,

                }
            },
            width: "40%",
            draggable: true,
            fullscreen: deviceDetection(),
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(editForm, { ref: formRef }),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;

                function chores(isAdd: Boolean) {
                    if (isAdd) {
                        NavAdd(curData).then((result) => {
                            if (result.success) {
                                feedback.msgSuccess("操作成功");
                                done(); // 关闭弹框
                                onSearch(); // 刷新表格数据
                            }
                        }).catch((err) => {
                            feedback.msgError(err.message ? err.message : `操作失败`);
                        });

                    } else {
                        NavEdit(curData).then((result) => {
                            if (result.success) {
                                feedback.msgSuccess(`操作成功`);
                                done(); // 关闭弹框
                                onSearch(); // 刷新表格数据
                            }
                        }).catch((err) => {
                            feedback.msgError(err.message ? err.message : `操作失败`);
                        });
                    }
                }

                FormRef.validate(valid => {
                    if (valid) {
                        console.log("curData", curData);
                        // 表单规则校验通过
                        if (title === "新增") {
                            chores(true)
                        } else {
                            chores(false)
                        }
                    }
                });
            }
        });
    }

    function handleDelete(row) {

        NavDelete(row.deptId).then((result) => {
            feedback.msgSuccess("操作成功")
            onSearch();
        }).catch((err) => {
            feedback.msgError(err && err.message ? err.message : "操作失败")
        });

    }

    onMounted(() => {
        onSearch();
    });

    return {
        form,
        loading,
        columns,
        dataList,
        optionsData,
        /** 搜索 */
        onSearch,
        /** 重置 */
        resetForm,
        /** 新增、修改 */
        openDialog,
        /** 删除 */
        handleDelete,
        handleSelectionChange
    };
}